# Definition for a binary tree node.
from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        vals = []

        def dfs(root: Optional[TreeNode]):
            nonlocal vals

            if root is None:
                return
            if root.left:
                dfs(root.left)
            vals.append(root.val)
            if root.right:
                dfs(root.right)

        dfs(root)
        return vals[k - 1]